<template>
  <div class="merchant-products">
    <a-card>
      <!-- 搜索表单 -->
      <a-form :model="searchForm" layout="inline">
        <a-form-item field="keyword" label="商品名称">
          <a-input
            v-model="searchForm.keyword"
            placeholder="请输入商品名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="category" label="商品分类">
          <a-select
            v-model="searchForm.category"
            placeholder="请选择商品分类"
            allow-clear
          >
            <a-option value="food">特色美食</a-option>
            <a-option value="souvenir">旅游纪念品</a-option>
            <a-option value="craft">手工艺品</a-option>
            <a-option value="cultural">文创产品</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="商品状态">
          <a-select
            v-model="searchForm.status"
            placeholder="请选择商品状态"
            allow-clear
          >
            <a-option value="on">在售</a-option>
            <a-option value="off">下架</a-option>
            <a-option value="sold_out">售罄</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <a-space>
          <a-button type="primary" @click="handleCreate">
            <template #icon><icon-plus /></template>
            新增商品
          </a-button>
          <a-button type="primary" status="warning" @click="handleBatchOffline">
            <template #icon><icon-pause-circle /></template>
            批量下架
          </a-button>
          <a-button type="primary" status="success" @click="handleBatchOnline">
            <template #icon><icon-play-circle /></template>
            批量上架
          </a-button>
          <a-button type="primary" status="danger" @click="handleBatchDelete">
            <template #icon><icon-delete /></template>
            批量删除
          </a-button>
        </a-space>
      </div>

      <!-- 商品表格 -->
      <a-table
        :loading="loading"
        :data="productList"
        :pagination="pagination"
        :row-selection="rowSelection"
        @page-change="handlePageChange"
      >
        <template #columns>
          <a-table-column title="商品信息">
            <template #title>
              商品信息
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('name', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button size="mini" @click="handleSort('name', 'desc')">
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="product-info">
                <a-avatar :size="60" :src="record.image" />
                <div class="product-detail">
                  <div class="product-name">{{ record.name }}</div>
                  <div class="product-category">
                    {{ getCategoryText(record.category) }}
                  </div>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="价格" data-index="price">
            <template #title>
              价格
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('price', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button size="mini" @click="handleSort('price', 'desc')">
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
            <template #cell="{ record }">
              <span class="price">¥{{ record.price }}</span>
            </template>
          </a-table-column>
          <a-table-column title="库存" data-index="stock">
            <template #title>
              库存
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('stock', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button size="mini" @click="handleSort('stock', 'desc')">
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
            <template #cell="{ record }">
              <span :class="{ 'stock-warning': record.stock < 10 }">
                {{ record.stock }}
              </span>
            </template>
          </a-table-column>
          <a-table-column title="销量" data-index="sales">
            <template #title>
              销量
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('sales', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button size="mini" @click="handleSort('sales', 'desc')">
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime">
            <template #title>
              创建时间
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('createTime', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button size="mini" @click="handleSort('createTime', 'desc')">
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="操作" width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-button
                  v-if="record.status === 'on'"
                  type="text"
                  status="warning"
                  size="small"
                  @click="handleOffline(record)"
                >
                  下架
                </a-button>
                <a-button
                  v-if="record.status === 'off'"
                  type="text"
                  status="success"
                  size="small"
                  @click="handleOnline(record)"
                >
                  上架
                </a-button>
                <a-popconfirm
                  content="确定要删除该商品吗？"
                  @ok="handleDelete(record)"
                >
                  <a-button type="text" status="danger" size="small">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import { IconUp, IconDown } from "@arco-design/web-vue/es/icon";

const router = useRouter();

// 搜索表单数据
const searchForm = reactive({
  keyword: "",
  category: "",
  status: "",
});

// 表格数据
const loading = ref(false);
const productList = ref([
  {
    id: 1,
    name: "特色桂花糕",
    category: "food",
    image: "https://example.com/image1.jpg",
    price: 299.0,
    stock: 8,
    sales: 328,
    status: "on",
    createTime: "2024-03-15 12:34:56",
  },
  // 更多商品数据...
]);

// 分页配置
const pagination = reactive({
  total: 100,
  current: 1,
  pageSize: 10,
});

// 表格选择配置
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
});

// 获取分类文本
const getCategoryText = (category) => {
  const categoryMap = {
    food: "特色美食",
    souvenir: "旅游纪念品",
    craft: "手工艺品",
    cultural: "文创产品",
  };
  return categoryMap[category] || "未知分类";
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    on: "green",
    off: "red",
    sold_out: "gray",
  };
  return colorMap[status] || "default";
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    on: "在售",
    off: "已下架",
    sold_out: "售罄",
  };
  return textMap[status] || "未知状态";
};

// 搜索
const handleSearch = () => {
  console.log("搜索条件：", searchForm);
  // TODO: 调用接口获取数据
};

// 重置
const handleReset = () => {
  searchForm.keyword = "";
  searchForm.category = "";
  searchForm.status = "";
  handleSearch();
};

// 新增商品
const handleCreate = () => {
  router.push({ name: "MerchantProductCreate" });
};

// 编辑商品
const handleEdit = (record) => {
  router.push({
    name: "MerchantProductEdit",
    params: { id: record.id },
  });
};

// 下架商品
const handleOffline = (record) => {
  // TODO: 调用下架接口
  Message.success("商品已下架");
};

// 上架商品
const handleOnline = (record) => {
  // TODO: 调用上架接口
  Message.success("商品已上架");
};

// 删除商品
const handleDelete = (record) => {
  // TODO: 调用删除接口
  Message.success("商品已删除");
};

// 批量下架
const handleBatchOffline = () => {
  // TODO: 调用批量下架接口
  Message.success("已批量下架所选商品");
};

// 批量上架
const handleBatchOnline = () => {
  // TODO: 调用批量上架接口
  Message.success("已批量上架所选商品");
};

// 批量删除
const handleBatchDelete = () => {
  // TODO: 调用批量删除接口
  Message.success("已批量删除所选商品");
};

// 分页变化
const handlePageChange = (page) => {
  pagination.current = page;
  handleSearch();
};

// 添加排序处理函数
const handleSort = (field, order) => {
  const sortedList = [...productList.value];
  sortedList.sort((a, b) => {
    let compareA = a[field];
    let compareB = b[field];

    // 处理特殊字段
    if (["price", "stock", "sales"].includes(field)) {
      compareA = parseFloat(compareA) || 0;
      compareB = parseFloat(compareB) || 0;
    } else if (field === "createTime") {
      compareA = new Date(compareA).getTime();
      compareB = new Date(compareB).getTime();
    }

    if (order === "asc") {
      return compareA > compareB ? 1 : -1;
    } else {
      return compareA < compareB ? 1 : -1;
    }
  });

  productList.value = sortedList;
};
</script>

<style lang="less" scoped>
.merchant-products {
  height: 100%;
  overflow-y: auto;

  .table-toolbar {
    margin: 16px 0;
  }

  .product-info {
    display: flex;
    align-items: center;

    .product-detail {
      margin-left: 12px;

      .product-name {
        font-weight: 500;
      }

      .product-category {
        font-size: 12px;
        color: var(--color-text-3);
        margin-top: 4px;
      }
    }
  }

  .price {
    color: #f53f3f;
    font-weight: 500;
  }

  .stock-warning {
    color: #f53f3f;
  }

  .sort-buttons {
    display: inline-flex;
    flex-direction: column;
    margin-left: 4px;
    vertical-align: middle;

    .arco-btn {
      padding: 0 4px;
      height: 14px;
      line-height: 14px;
      border: none;

      &:hover {
        background-color: var(--color-fill-3);
      }

      .arco-icon {
        font-size: 12px;
      }
    }
  }
}
</style>
